'use strict';

const axios = require('axios');
const semver = require('semver');
const urlJoin = require('url-join');


const defaultRegistry = 'https://registry.npm.taobao.org';  // 'https://registry.npmjs.org'; 有问题

/**
 * @method
 * @param {string} pkgName 包名
 * @param {string} registry npm源
 * @returns {Promise<any>}
 * @desc 获取pkgName信息
 */
function npmInfo(pkgName, registry = defaultRegistry) {
  if (pkgName) {
    const url = urlJoin(registry, pkgName);
    return axios.get(url).then(({ data }) => data);
  }
  return Promise.resolve(null);
}

// 查询所有版本号
function npmVersions(data) {
  if (data) {
    return Object.keys(data.versions);
  }
  return [];
}

// 筛选符合条件的版本号
function npmSemverVersions(currentVersion, versions) {
  return versions
    .filter(item => semver.satisfies(item, `^${currentVersion}`))
    .sort((a, b) => semver.gt(b, a));
}

async function npmLatestVersion(pkgName, registry = defaultRegistry) {
  const data = await npmInfo(pkgName, registry);
  let versions = npmVersions(data);
  if (versions.length) {
    return versions.sort((a, b) => semver.gt(b, a))[0];
  }
  return null;
}

module.exports = {
  npmInfo,
  npmVersions,
  defaultRegistry,
  npmSemverVersions,
  npmLatestVersion
};
